from subprocess import check_output,getstatusoutput,CalledProcessError
import psutil
import platform


def run_shell(cmd):
    (status,output) = getstatusoutput(cmd)
    context = {
        'status':status,
        'output':output,
    }
    return context

def get_sys_info():
    # disk_info = psutil.disk_usage('/').percent
    # cpu_info = psutil.cpu_percent(0)
    # memory_info = psutil.virtual_memory().percent
    # nginx_info = run_shell('nginx -v')['output'].split(': ')[1]
    # nginx_status = int(run_shell(r'ps -ef | grep nginx | wc -l')['output'])
    nic_info = []
    for nic,addrs in psutil.net_if_addrs().items():
        if ":" not in addrs[0].address:
            if nic != "lo":
                nic_info.append({'nic':nic,'address':addrs[0].address})
    sysinfo = {
        'nic' : nic_info,
        'platform' : {
            'node' : platform.node(),
            'system' : platform.system(),
            'release' : platform.release(),
            'processor' : platform.processor()
        },
        'nginx': run_shell('nginx -v')['output'].split(': ')[1]
    }
    return sysinfo

def get_sys_status():
    mem = psutil.virtual_memory()
    disk = psutil.disk_usage('/')
    nginx_status = False
    try:
        nginx_status = bool(len(check_output(["pidof","nginx"]).split()))
    except CalledProcessError:
        nginx_status = False

    statusinfo = {
        'cpu_percent':psutil.cpu_percent(),
        'mem_info':{
            'available':round(mem.available/1024.0/1024.0),
            'used':round((mem.used)/1024.0/1024.0),
            'total':round(mem.total/1024.0/1024.0),
        },
        'disk_info':{
            'total':round(disk.total/1024.0/1024.0/1024.0,2),
            'used':round(disk.used/1024.0/1024.0/1024.0,2),
        },
        'nginx_status':nginx_status
    }

    return statusinfo